//
//  SchedulingController.m
//  HarmonizePub
//
//  Created by rzhy on 16/9/13.
//  Copyright © 2016年 Zy. All rights reserved.
//


/**
 * You may think you know what the following code does.
 * But you dont. Trust me.
 * Fiddle with it, and youll spend many a sleepless.
 * night cursing the moment you thought youd be clever.
 * enough to "optimize" the code below.
 * Now close this file and go play with something else.
 *
 * 你可能会认为你读得懂以下的代码。但是你不会懂的，相信我吧.
 * 要是你尝试玩弄以下的代码的话，你将会在无尽的通宵中不断地咒骂自己为什么会认为自己聪明到可以优化这段代码.
 * 现在请关闭这个文件去玩点别的吧.
 */
/**
 * no comments for you.
 * it was hard to write.
 * so it should be hard to read.
 *
 * 难写的代码，肯定很难读。因此，我没有注释留给你.
 */


#import "SchedulingController.h"
#import "Config.h"
#import <UIScrollView+EmptyDataSet.h>
#import "SchedulingTableViewCell.h"
#import "CalendarButton.h"
#import "RegisterDoctorController.h"
#import "DoctorIntroduceController.h"

static NSString * const CellIdentifier = @"Cell";

@interface SchedulingController () <UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate, SchedulingCellDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
{
    NSString *_maxDay;
    NSDictionary *_dataDict;
    NSMutableArray *_showDataArray;
}
@property (weak, nonatomic) IBOutlet UIButton *allButton;
@property (weak, nonatomic) IBOutlet UIScrollView *headScrollView;
@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation SchedulingController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = _selectDataDict[@"ksmc"];
    self.headScrollView.contentSize = CGSizeMake((XHScreenWidth - 60.0) * self.pageControl.numberOfPages, 0);
    [self addHeadScrollTextView];
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
    UINib *nib = [UINib nibWithNibName:[SchedulingTableViewCell registerName] bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:CellIdentifier];
    [self getScheduleDoctorData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 添加ScrollView的子View
- (void)addHeadScrollTextView {
    NSUInteger dayCount = 7;
    CGFloat buttonY = 10.0f;
    CGFloat buttonW = (XHScreenWidth - 60) / dayCount;
    CGFloat buttonH = 80.0 - buttonY * 2 - 5;
    for (NSInteger i = 0; i < self.pageControl.numberOfPages * 7; i++) {
        NSDate *date = [[NSDate alloc] initWithTimeInterval:(i) * 24 * 60 * 60 sinceDate:[NSDate date]];
        CGRect rect = CGRectMake(i * buttonW, buttonY, buttonW, buttonH);
        CalendarButton *button = [self createCalendarButtonWithDate:date frame:rect];
        button.tag = i;
        [self.headScrollView addSubview:button];
        if (i == self.pageControl.numberOfPages * dayCount - 1)
            _maxDay = [NSString stringAnalysisWithDate:date format:@"yyyyMMdd"];
    }
}

#pragma mark - createCalendarButton
- (CalendarButton *)createCalendarButtonWithDate:(NSDate *)date frame:(CGRect)frame {
    CalendarButton *button = [CalendarButton calendarButton];
    button.enabled = NO;
    // text
    [button setTitle:[NSString stringWeekdayWithFromDate:date weekType:WeekdayDateStringTypeNumber] forState:UIControlStateNormal];
    button.lable.text = [NSString stringAnalysisWithDate:date format:@"dd"];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button setTitleColor:RGBColor(39, 155, 219) forState:UIControlStateSelected];
    // font
    button.lable.font = [UIFont systemFontOfSize:15.0f];
    button.titleLabel.font = [UIFont systemFontOfSize:17.0f];
    // image
    [button setImage:[UIImage imageNamed:@"Blueround.png"] forState:UIControlStateSelected];
    [button setImage:[UIImage imageNamed:@"Grayround.png"] forState:UIControlStateDisabled];
    button.frame = frame;
    [button addTarget:self action:@selector(calendarButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    return button;
}

#pragma mark - 按钮点击事件
#pragma mark 全部
- (IBAction)allButtonEvent:(UIButton *)sender {
    [self calendarButtonEvent:nil];
    sender.selected = YES;
    [self filtrationDataWithDateString:@"全部" dataArray:_dataDict[@"docList"]];
}

#pragma mark 日期
- (void)calendarButtonEvent:(CalendarButton *)sender {
    if (self.allButton.selected) self.allButton.selected = NO;
    if (sender.selected) return ;
    for (UIButton *button in _headScrollView.subviews)
        if ([button isKindOfClass:[UIButton class]])
            if (button.selected && button.enabled)
                button.selected = NO;
    sender.selected = !sender.selected;
    [self filtrationDataWithDateString:sender.lable.text dataArray:_dataDict[@"docList"]];
}

#pragma mark - 排班数据
- (void)getScheduleDoctorData {
    NSDictionary *param = @{@"ksdm" : _selectDataDict[@"ksdm"]};
//    XHLog(@"param: %@", param);
    __unsafe_unretained SchedulingController *weakSelf = self;
    [HTTPSTool GETRequestWithPath:XHGetOrderDpPbPath params:param success:^(NSDictionary * _Nonnull JSON) {
//        XHLog(@"预约挂号医生列表 -> JSON: %@", JSON)
        _dataDict = JSON[@"data"];
        [weakSelf setButtonAttr];
    }];
}
/**    
 * When I wrote this, only God and I understood what I was doing.
 * Now, God only knows.
 *    
 * 写这段代码的时候，只有上帝和我知道它是干嘛的.
 * 现在，只有上帝知道.
 */
- (void)setButtonAttr {
    BOOL isSelect = YES;
    for (CalendarButton *button in self.headScrollView.subviews)
        if ([button isKindOfClass:[CalendarButton class]])
            for (NSDictionary *dataDict in _dataDict[@"docList"]) {
                for (NSDictionary *pbDict in dataDict[@"pbList"]) {
                    for (NSDictionary *dict in pbDict[@"pb"]) {
                        NSString *jzrq = dict[@"jzrq"];
                        NSString *time = [jzrq stringInterceptWithBegin:jzrq.length - 2 end:jzrq.length];
                        if ([time isEqualToString:button.lable.text]) {
                            button.enabled = YES;
                            if (isSelect) {
                                [self calendarButtonEvent:button];
                                isSelect = NO;
                            }
                        }
                    }
                }
            }
}
/**    
 * When I wrote this, only God and I understood what I was doing.
 * Now, God only knows.
 *    
 * 写这段代码的时候，只有上帝和我知道它是干嘛的.
 * 现在，只有上帝知道.
 */
- (void)filtrationDataWithDateString:(NSString *)dateString dataArray:(NSArray *)dataArray {
    if (!dataArray.count) return ;
    if (!_showDataArray) _showDataArray = [NSMutableArray arrayWithCapacity:dataArray.count];
    else [_showDataArray removeAllObjects];
    NSMutableArray *oneArray = [NSMutableArray array];
    NSMutableArray *twoArray = [NSMutableArray array];
    for (NSDictionary *dataDict in dataArray) {
        for (NSDictionary *pbListDict in dataDict[@"pbList"]) {
            for (NSInteger i = 0; i < [pbListDict[@"pb"] count]; i++) {
                NSDictionary *pbDict = pbListDict[@"pb"][i];
                NSString *jzrq = pbDict[@"jzrq"];
                NSString *time = [jzrq stringInterceptWithBegin:jzrq.length - 2 end:jzrq.length];
                NSDictionary *dict = [self setDoctorDataWithDataDictionary:dataDict pbDict:pbDict date:dateString];
                if ([dateString isEqualToString:@"全部"]) {
                    if (oneArray.count) {
                        for (NSInteger i = 0; i < oneArray.count; i++) {
                            NSDictionary *docDict = oneArray[i];
                            if ([docDict[@"ygdm"] isEqualToString:dict[@"ygdm"]])
                                break ;
                            else
                                if (i == oneArray.count - 1)
                                    [oneArray addObject:dict];
                        }
                    } else {
                        [oneArray addObject:dict];
                    }
                } else {
                    if ([time isEqualToString:dateString]) {
                        [oneArray addObject:dict];
                        break ;
                    } else {
                        if (i == [pbListDict[@"pb"] count] - 1)
                            [twoArray addObject:dict];
                    }
                }
            }
        }
    }
    _showDataArray = oneArray;
    for (NSDictionary *dict in twoArray)
         [_showDataArray addObject:dict];
    [_tableView reloadData];
}
/**    
 * When I wrote this, only God and I understood what I was doing.
 * Now, God only knows.
 *    
 * 写这段代码的时候，只有上帝和我知道它是干嘛的.
 * 现在，只有上帝知道.
 */
- (NSDictionary *)setDoctorDataWithDataDictionary:(NSDictionary *)dataDict pbDict:(NSDictionary *)pbDict date:(NSString *)date {
    NSMutableArray *arrayM = [NSMutableArray array];
    for (NSDictionary *dict in _dataDict[@"docList"])
        if ([dict[@"ygdm"] isEqualToString:pbDict[@"ygdm"]])
            for (NSDictionary *dataD in dict[@"pbList"]) {
                for (NSDictionary *pbDict in dataD[@"pb"]) {
                    NSString *jzrq = pbDict[@"jzrq"];
                    NSString *time = [jzrq stringInterceptWithBegin:jzrq.length - 2 end:jzrq.length];
                    if ([date isEqualToString:@"全部"])
                        // 全部
                        [arrayM addObject:pbDict];
                    else
                        if ([time isEqualToString:date])
                            [arrayM addObject:pbDict];
                }
            }
    [arrayM addObject:@{@"text" : @"查看排班"}];
    NSString *image = [NSString stringDeleteNullWithString:dataDict[@"image"]];
    NSString *description = [NSString stringDeleteNullWithString:dataDict[@"description"]];
    NSDictionary *dict = @{@"image" : image, 
                           @"description" : description, 
                           @"pblsh" : pbDict[@"pblsh"], 
//                           @"ycpb" : pbDict[@"ycpb"], 
                           @"ygxm" : pbDict[@"ygxm"], 
                           @"sdbz" : pbDict[@"sdbz"], 
                           @"jzrq" : pbDict[@"jzrq"], 
                           @"ksdm" : self.selectDataDict[@"ksdm"], 
                           @"ygdm" : pbDict[@"ygdm"], 
//                           @"sdbzValue" : pbDict[@"sdbzValue"],
                           @"timeArray" : arrayM};
    return dict;
}

#pragma mark scrollView delegate
- (void)scrollViewDidScroll:(UIScrollView * _Nonnull)scrollView {
    self.pageControl.currentPage = scrollView.contentOffset.x / scrollView.frame.size.width;
}

#pragma mark - tableView Delegate/DataSource Method
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _showDataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [SchedulingTableViewCell cellHeightWithDataDictionary:_showDataArray[indexPath.section]];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.001f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SchedulingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell.delegate = self;
    cell.dataDict = _showDataArray[indexPath.section];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSDictionary *dict = _showDataArray[indexPath.section];
    [self jumpDoctorControllerWithDataDictionary:dict selectIndex:0];
}

- (void)schedulingCell:(SchedulingTableViewCell *)schedulingCell didSelectItemAtDictionary:(NSDictionary *)dict timeDict:(NSDictionary *)timeDict {
    NSString *text = timeDict[@"text"];
    NSIndexPath * index_fuck = [_tableView indexPathForCell:schedulingCell];
    for (NSDictionary *dataDict in _dataDict[@"docList"])
        if ([dict[@"ygdm"] isEqualToString:dataDict[@"ygdm"]])
            dict = dataDict;
    if (text) {
        [self jumpDoctorControllerWithDataDictionary:dict selectIndex:1];
    } else {
        RegisterDoctorController *registerDoctor = [[RegisterDoctorController alloc] init];
        registerDoctor.selectDay = timeDict[@"pblsh"];
        registerDoctor.maxDay = _maxDay;
        registerDoctor.depName = self.title;
//        registerDoctor.dataDict = dict;
        registerDoctor.dataDict = _showDataArray[index_fuck.section];
        [self.navigationController pushViewController:registerDoctor animated:YES];
    }
}

- (void)jumpDoctorControllerWithDataDictionary:(NSDictionary *)dataDict selectIndex:(NSInteger)index {
//    XHLog(@"%@", dataDict)
    DoctorIntroduceController *doctor = [[DoctorIntroduceController alloc] init];
    doctor.selectIndex = index;
    doctor.ksdm = dataDict[@"ksdm"];
    doctor.ygdm = dataDict[@"ygdm"];
    [self.navigationController pushViewController:doctor animated:YES];
}

#pragma mark - DZNEmptyDataSetSource Method
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    UIImage *image = [UIImage imageNamed:@"LoadFailure.png"];
    return image;
}

- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *string = XHEmptyDes;
    NSAttributedString *abs = [[NSAttributedString alloc] initWithString:string attributes:nil];
    return abs;
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return -64.0f;
}

#pragma mark - DZNEmptyDataSetDelegate Method
- (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView {
    return YES;
}

- (BOOL)emptyDataSetShouldAllowTouch:(UIScrollView *)scrollView {
    return YES;
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    [self getScheduleDoctorData];
}

@end
